/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 广告编辑
 */
import React, { useState, useEffect, useCallback } from 'react';
import { Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormDependency,
} from '@ant-design/pro-form';
import UploadWithCrypto from '@base/components/upload-width-crypto';
import { createAdv, editAdv, copyAdv } from '@/services/operatorManagement';
import PreviewTemplate from './PreviewTemplate';
import type { AdvTableListItem } from '../types/Advertisements';

interface AdvEditTypes {
  visible: boolean;
  type: 'add' | 'edit';
  record: AdvTableListItem;
  onClose: () => void;
  getList: () => void;
}

const formFields = [
  'type',
  'platform',
  'brand',
  'name',
  'custom_area_words',
  'custom_area_url',
  'ad_area_img',
  'ad_area_url',
  'note',
];

const AdvEdit: React.FC<AdvEditTypes> = ({ visible, type, onClose, record, getList }) => {
  const [advType, setAdvType] = useState<'orderSheet' | 'pickUpCode'>('orderSheet');
  const [imgSrc, setImgSrc] = useState<string>('');
  const [submiting, setSubmiting] = useState<boolean>(false);
  const [form] = ProForm.useForm();

  useEffect(() => {
    if (visible && type === 'edit') {
      setImgSrc(record.ad_area_img);
      setAdvType(record.platform == '1' ? 'orderSheet' : 'pickUpCode');
      form?.setFieldsValue({
        brand: record.brand,
        name: record.name,
        custom_area_words: record.custom_area_words,
        custom_area_url: record.custom_area_url,
        ad_area_url: record.ad_area_url,
        note: record.note,
      });
    }
    form?.setFieldsValue({
      platform: record.platform || '1',
    });
  }, [visible, type, record, form]);

  const onPreview = useCallback(() => {
    const imgChanged = form.isFieldTouched('ad_area_img');
    let arr = [...formFields];
    if (type === 'edit' && !imgChanged) {
      arr = formFields.filter((i) => i != 'ad_area_img');
    }
    return new Promise((resolve, reject) => {
      form
        .validateFields(arr)
        .then((res) => {
          resolve({
            ...res,
            status: '2',
            ad_area_img: imgSrc,
          });
        })
        .catch((error) => {
          reject(error);
        });
    });
  }, [imgSrc, type, form]);

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 PNG 格式的图片');
      return false;
    }
    return true;
  };

  const onCancel = useCallback(() => {
    onClose();
    setAdvType('orderSheet');
    setImgSrc('');
    form.resetFields();
  }, [form, onClose]);

  const onUploadChange: (info: any) => void = (info) => {
    const { file = {} } = info;
    if (file.status == 'done') {
      const { response = {} } = file;
      if (response.code == 0) {
        setImgSrc(response.data);
      } else {
        message.error(response.msg);
      }
    }
  };

  const onSubmit = useCallback(() => {
    setSubmiting(true);
    const payload = {
      ad_area_img: imgSrc,
      id: type === 'edit' ? record.id : undefined,
      status: '2',
    };
    const submitter = type === 'edit' ? editAdv : createAdv;
    const imgChanged = form.isFieldTouched('ad_area_img');
    const isAllChanged = form.isFieldsTouched(formFields);
    if (!isAllChanged) {
      setSubmiting(false);
      onCancel();
      return;
    }
    let arr = [...formFields];

    // 编辑时，对上传列表不进行校验
    if (type === 'edit' && !imgChanged) {
      arr = formFields.filter((i) => i != 'ad_area_img');
    }

    form
      .validateFields(arr)
      .then(async (res) => {
        const { code, msg } = await submitter({
          ...res,
          ...payload,
        });
        setSubmiting(false);
        if (code == 0) {
          message.success('提交成功');
          onCancel();
          getList();
        } else {
          message.error(msg);
        }
      })
      .catch(() => {
        setSubmiting(false);
      });
  }, [imgSrc, type, record, form, getList, onCancel]);

  const onCopy = useCallback(async () => {
    const { code, msg } = await copyAdv({ id: record.id });
    if (code == 0) {
      message.success('复制成功');
      onCancel();
      getList();
    } else {
      message.error(msg);
    }
  }, [record, getList, onCancel]);

  return (
    <ModalForm
      form={form}
      visible={visible}
      title='发布新广告'
      layout='horizontal'
      width={800}
      submitter={{
        render: () => [
          <PreviewTemplate type={advType} key='preview' onPreview={onPreview}>
            生成预览
          </PreviewTemplate>,
          <Button loading={submiting} type='primary' key='save' onClick={onSubmit}>
            {type === 'add' ? '发布' : '保存'}
          </Button>,
          <span key='copy'>{type === 'edit' && <Button onClick={onCopy}>复制</Button>}</span>,
        ],
      }}
      modalProps={{
        centered: true,
        onCancel,
      }}
      onValuesChange={(changedValues) => {
        if (changedValues.platform) {
          setAdvType(changedValues.platform == 1 ? 'orderSheet' : 'pickUpCode');
          form.setFieldsValue({
            brand: undefined,
          });
        }
      }}
    >
      <ProFormDependency name={['platform']}>
        {({ platform }) => {
          const isnNormalOrder = platform === '1'; // 是否是面单
          let positionInfoOptions: any[] = [];
          switch (platform) {
            case '1':
              positionInfoOptions = [
                {
                  label: '快宝面单',
                  value: 'kb',
                },
                {
                  label: '菜鸟面单',
                  value: 'cn',
                },
              ];
              break;
            case '2':
              positionInfoOptions = [
                {
                  label: '快宝取件码',
                  value: 'kb',
                },
              ];
              break;
            case '3':
              positionInfoOptions = [
                {
                  label: '快宝面单',
                  value: 'kb',
                },
              ];
              break;
            default:
              positionInfoOptions = [];
              break;
          }
          return (
            <>
              <ProForm.Group>
                <ProFormSelect
                  initialValue='1'
                  options={[
                    {
                      label: '线下',
                      value: '1',
                    },
                  ]}
                  width='xs'
                  name='type'
                  label='平台类型'
                  rules={[
                    {
                      required: true,
                      message: '请选择平台类型',
                    },
                  ]}
                />
                <ProFormSelect
                  allowClear={false}
                  width='xs'
                  options={[
                    {
                      label: '面单',
                      value: '1',
                    },
                    {
                      label: '取件码',
                      value: '2',
                    },
                    {
                      label: '一联单',
                      value: '3',
                    },
                  ]}
                  name='platform'
                  label='广告平台'
                  rules={[
                    {
                      required: true,
                      message: '请选择广告平台',
                    },
                  ]}
                />
                <ProFormSelect
                  width='sm'
                  options={positionInfoOptions}
                  name='brand'
                  label='广告位置'
                  rules={[
                    {
                      required: true,
                      message: '请选择广告位置',
                    },
                  ]}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText
                  width='lg'
                  name='name'
                  label='广告名称'
                  placeholder='请输入广告名称'
                  rules={[
                    {
                      required: true,
                      message: '请输入广告名称',
                    },
                  ]}
                />
              </ProForm.Group>
              {isnNormalOrder && (
                <>
                  <ProForm.Group>
                    <ProFormText
                      width='lg'
                      name='custom_area_words'
                      label='自定义区域文案'
                      placeholder='请输入文案'
                      rules={[
                        {
                          required: true,
                          message: '请输入文案',
                        },
                      ]}
                    />
                  </ProForm.Group>
                  <ProForm.Group>
                    <ProFormText
                      width='lg'
                      name='custom_area_url'
                      label='自定义区域链接'
                      placeholder='以https开头'
                      rules={[
                        {
                          required: true,
                          message: '请输入自定义区域链接',
                        },
                      ]}
                    />
                  </ProForm.Group>
                </>
              )}
              <ProForm.Group>
                <img
                  src={imgSrc}
                  alt='广告区域图片'
                  style={{
                    width: 458,
                    height: 100,
                    marginLeft: 0,
                    marginBottom: 30,
                    maxWidth: '100%',
                  }}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProForm.Item
                  label='广告区域图片'
                  name='file'
                  extra='扩展名仅限：png，图片尺寸为：458 * 100'
                  rules={[
                    {
                      required: true,
                      message: '请上传广告区域图片',
                    },
                  ]}
                >
                  <UploadWithCrypto
                    action='/CloudPrintAd/upload'
                    onChange={onUploadChange}
                    accept='image/png'
                    beforeUpload={beforeUpload}
                    showUploadList={false}
                    maxCount={1}
                  >
                    <Button icon={<UploadOutlined />}>上传图片</Button>
                  </UploadWithCrypto>
                </ProForm.Item>
              </ProForm.Group>

              <ProForm.Group>
                <ProFormText
                  width='lg'
                  name='ad_area_url'
                  label='广告区域链接'
                  placeholder='以https开头'
                  rules={[
                    {
                      required: true,
                      message: '请输入广告区域链接',
                    },
                  ]}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormText width='lg' name='note' label='备注' placeholder='请输入备注' />
              </ProForm.Group>
            </>
          );
        }}
      </ProFormDependency>
    </ModalForm>
  );
};

export default React.memo(AdvEdit);
